package edu.hit.pact.pgse.client;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import edu.hit.pact.pgse.bean.Task;
import edu.hit.pact.pgse.bean.TaskPieceStatistics;
import edu.hit.pact.pgse.communication.message.AbstractMessage;
import edu.hit.pact.pgse.communication.message.TaskPushMessage;
import edu.hit.pact.pgse.util.Globals;

public class ClientManager {
	private Log logger;
	private IoSession masterSession;
	private PrintWriter finishTracker ;
	private SimpleDateFormat formater;
	
	public ClientManager(){
		logger = LogFactory.getLog(ClientManager.class);
		try {
			finishTracker = new PrintWriter(new FileOutputStream("finish", true), true);
			formater = new SimpleDateFormat("yyyy-MM-dd*hh:mm:ss");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setMasterSession(IoSession session){
		logger.info("set session with master");
		this.masterSession = session;
	}
	
	public void processFinishedNotify(TaskPieceStatistics statistics){
		logger.error(statistics);
		finishTracker.println(formater.format(statistics.getStartTime()) + "\t" + statistics.getHomePage() + "\t" +statistics.getSucceededPageNumber() + "\t" + 
				formater.format(statistics.getFinishedTime()) + "\t" + (statistics.getFinishedTime() - statistics.getStartTime())/1000);
	}
	
	public void pushWebTask() {
		logger.info("pushWebTask");
		System.out.println(Globals.TIME_WEB_TASK_CRAWL_HOUR+"-"+Globals.TIME_WEB_TASK_CRAWL_MINUTE+"-"+Globals.INTERVAL_CRAWL_WEB_TASK);
		Task task = new Task(TaskPiecesConstructor.webPieceGen("conf/task_web"));
		AbstractMessage message = new TaskPushMessage(task);
		masterSession.write(message);
	}
	
	public void pushBlogTask() {
		logger.info("pushBlogTask");
		System.out.println(Globals.TIME_BLOG_TASK_CRAWL_HOUR+"-"+Globals.TIME_BLOG_TASK_CRAWL_MINUTE+"-"+Globals.INTERVAL_CRAWL_BLOG_TASK);
		Task task = new Task(TaskPiecesConstructor.blogPieceGen("conf/task_blog"));
		AbstractMessage message = new TaskPushMessage(task);
		masterSession.write(message);
	}
	
	public void pushBbsTask() {
		logger.info("pushBbsTask");
		System.out.println(Globals.TIME_BBS_TASK_CRAWL_HOUR+"-"+Globals.TIME_BBS_TASK_CRAWL_MINUTE+"-"+Globals.INTERVAL_CRAWL_BBS_TASK);
		Task task = new Task(TaskPiecesConstructor.bbsPieceGen("conf/task_bbs"));
		AbstractMessage message = new TaskPushMessage(task);
		masterSession.write(message);
	}
}
